<template>
  <div class="login-container">
    <div class="box">
      <img src="../../assets/login-location.png" alt="" class="img" />
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        auto-complete="on"
        label-position="top"
      >
        <div class="title-container">
          <h3 class="title">登录</h3>
        </div>

        <el-form-item prop="username" label="账号：" class="admin">
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="请输入账号"
            name="username"
            tabindex="1"
            clearable
            auto-complete="on"
          />
        </el-form-item>

        <el-form-item prop="password" label="密码：" class="passWord">
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="请输入密码"
            name="password"
            tabindex="2"
            auto-complete="on"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            />
          </span>
        </el-form-item>
        <p class="forgetPwd" @click="openCreateInfo">创建用户</p>
        <el-button
          class="btn"
          :loading="loading"
          type="primary"
          @click.native.prevent="handleLogin"
          >登录</el-button
        >
        <!-- <div class="tips">
          <p class="text1">还没注册账号？<span class="text2">创建账号</span></p>
        </div> -->
      </el-form>
    </div>
    <el-dialog
      class="dialog"
      title="创建用户"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-form class="form" ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户昵称" prop="nickName">
          <el-input
            size="small"
            clearable
            v-model="form.nickName"
            placeholder="请输入用户昵称"
            maxlength="30"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            size="small"
            clearable
            v-model="form.phonenumber"
            placeholder="请输入手机号码"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            size="small"
            clearable
            v-model="form.email"
            placeholder="请输入邮箱"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item
          v-if="form.userId == undefined"
          label="用户名称"
          prop="userName"
        >
          <el-input
            size="small"
            clearable
            v-model="form.userName"
            placeholder="请输入用户名称"
            maxlength="30"
          />
        </el-form-item>
        <el-form-item
          v-if="form.userId == undefined"
          label="用户密码"
          prop="password"
        >
          <el-input
            size="small"
            clearable
            v-model="form.password"
            placeholder="请输入用户密码"
            type="password"
            maxlength="20"
            show-password
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleClose">取 消</el-button>
        <el-button size="small"
          type="primary"
          @click="save"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import { addGuest } from '@/api/user'
import { createSocket } from '@/api/websocket'
import { mapGetters } from 'vuex'
export default {
  name: 'Login',
  computed: {
    ...mapGetters(['activeName', 'menu'])
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('账号不能为空'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 4) {
        callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    return {
      form: {},
      rules: {
        userName: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '用户昵称不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        email: [
          {
            type: 'email',
            message: "请输入正确的邮箱地址",
            trigger: ['blur', 'change']
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      },
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [
          // { required: true, trigger: 'blur', validator: validateUsername }
          { required: true, message: '账号名称不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        password: [
          // { required: true, trigger: 'blur', validator: validatePassword }
          { required: true, message: '账号密码不能为空', trigger: 'blur' },
          { min: 5, max: 20, message: '账号密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      dialogVisible: false
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          console.log(wsUrl,'wsUrl-login');
          this.$store
            .dispatch('user/login', this.loginForm)
            .then(async() => {
              if (Object.keys(this.activeName) && Object.keys(this.activeName).length > 0) {
                this.$router.push({ path: this.activeName.path })
              }
              if (this.$store.state.user.menu && this.$store.state.user.menu.length === 0) {
                const res = await this.$store.dispatch('user/menuList')
                await this.$store.dispatch('user/getInfo')
                if (res[0].children) {
                  this.$router.push({ name: this.redirect || res[0].children[0].name })
                } else {
                  console.log('跳转至首页...');
                  this.$router.push({ path: this.redirect || '/' })
                }
              }
              // this.$router.push({ path: this.redirect || '/' })
              createSocket()
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    openCreateInfo() {
      this.dialogVisible = true
    },
    handleClose() {
      this.form = {}
      this.$refs['form'].resetFields()
      this.dialogVisible = false
    },
    save() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          addGuest(this.form).then(res => {
            if (res.code === 200) {
              this.dialogVisible = true
              this.handleClose()
              this.$message.success('创建成功！')
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
$bg: #283443;
$light_gray: #fff;
$cursor: #fff;
.login-container {
  .box{
    .el-input {
      display: inline-block;
      height: 47px;
      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        // color: $light_gray;
        height: 47px;
        caret-color: #fff; //改变输入框光标颜色,同时又不改变输入框里面的内容的颜色
        font-size: 16px;

        &:-webkit-autofill {
          box-shadow: 0 0 0 3rem #1c3a56 inset !important;
          -webkit-text-fill-color: #fff !important;
        }
      }
    }
    .admin {
      .el-form-item__label {
        &::before {
          content: "" !important;
          display: inline-block;
          background-image: url("@/assets/账号.png") !important;
          background-size: cover;
          width: 0.18rem;
          height: 0.16rem;
        }
      }
    }
    .passWord {
      .el-form-item__label {
        &::before {
          content: "" !important;
          display: inline-block;
          background-image: url("@/assets/密码.png") !important;
          background-size: cover;
          width: 0.18rem;
          height: 0.16rem;
        }
      }
    }

    .el-form-item {
      margin-bottom: 10px;
      .el-form-item__content {
        background: #1c3a56;
        border-bottom: 0.03rem solid;
        border-image-source: linear-gradient(45deg, #04f2db 0%, #0d8aff 100%);
        border-image-slice: 1;
        width: 80%;
      }
      .el-form-item__label {
        color: #fff;
      }
      .el-input__inner {
        color: #fff;
      }
    }
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  background-color: #1f3242;
  height: 100%;
  width: 100%;
  overflow: hidden;
  .box {
    width: 55%;
    box-sizing: border-box;
    height: 70%;
    display: flex;
    margin: auto;
    padding: 0.125rem 0.1rem;
    padding-bottom: 0.12rem;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    position: absolute;
    background-image: url("@/assets/login-bgc.png");
    background-repeat: no-repeat;
    background-size: 100% 100%;
    .img {
      width: 60%;
      height: 100%;
    }
    .login-form {
      // position: absolute;
      // transform: translate(11%,-50%);
      // left: 50%;
      width: 40%;
      padding-left: 0.62rem;
      background: url("@/assets/login-info.png");
      background-repeat: no-repeat;
      background-size: 100% 104.5%;
      height: 100%;
      // max-width: 100%;
      // box-sizing: border-box;
      // overflow: hidden;
      // height: 65%;
      // top: 50%;
    }

    .tips {
      font-size: 12px;
      text-align: left;
      height: 30px;
      line-height: 30px;
      position: absolute;
      bottom: 10px;
      .text1 {
        font-family: "PingFang SC ", "PingFang SC", sans-serif;
        font-weight: 400;
        color: #8494a9;
        .text2 {
          font-family: "PingFang SC ", "PingFang SC", sans-serif;
          font-weight: 650;
          color: #0480f7;
          cursor: pointer;
        }
      }
    }
    .btn {
      width: 80%;
      height: 38px;
      background: linear-gradient(228deg, #0a88ff 0%, #05f1db 100%);
      box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.25);
      border-radius: 6px 6px 6px 6px;
      margin-top: 0.42rem;
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }
    .el-form-item {
      position: relative;
    }

    .title-container {
      height: 1.5rem;

      .title {
        font-size: 24px;
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 500;
        color: #ffffff;
        text-align: left;
        line-height: 1.5rem;
      }
      .text {
        height: 40px;
        color: #8494a9;
        width: 100%;
        text-align: center;
      }
    }

    .line {
      position: absolute;
      display: inline-block;
      width: 5px;
      height: 52px;
      background: inherit;
      background-color: rgba(6, 127, 250, 1);
      border: none;
      border-radius: 0px;
      -webkit-box-shadow: none;
      box-shadow: none;
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }
    .forgetPwd {
      font-size: 12px;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 400;
      color: rgba(240, 245, 255, 0.8);
      text-align: right;
      width: 80%;
      line-height: 0.2rem;
      cursor: pointer;
    }
  }
  .dialog{
    .form{
      width: 80%;
      margin: 0 auto;
    }
    :deep(.el-form-item__label){
      color: #fff;
    }
    :deep(.el-input){
      caret-color: #fff;
    }
    :deep(.el-input__inner){
      background: transparent;
      color: #fff;
    }
  }
}

:deep(.el-dialog) {
  background: rgba(0, 28, 55, 0.85);
}
:deep(.el-dialog__header) {
  border-bottom: 1px solid rgba(120, 189, 255, 1);
  margin-right: 0px;
  margin-bottom: 10px;
}
:deep(.el-dialog__title) {
  color: #41b0ff;
  font-size: 16px;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: rgba(70, 174, 255, 1);
}
:deep(.el-textarea__inner) {
  background: rgb(51, 91, 127);
  box-shadow: none;
  border: none;
  color: #fff;
}
</style>
